import type { ProColumns } from '@ant-design/pro-components';
import {ActionType, EditableProTable, nanoid, PageContainer, ProForm, ProFormText} from '@ant-design/pro-components';
import {Form, message, Card, Typography, Row, Col, Space, DatePicker, Button, Upload, Modal} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import { history } from 'umi';
import {
  DisciInfluenceApi,
  DownloadApi,
  FillApi, GetSaveApi, SaveApi,
  SchoolCheckShow,
  ShowApi,
  UploadApi
} from "@/services/School/SchoolApi";
import {ServerMessages} from "@/services/ServerMessages";
import {getYear, ShowError} from "@/utils/format";
import {DownloadOutlined, UploadOutlined} from "@ant-design/icons";
import Submitter from "@/pages/Syl/Common/Submitter";
import moment from "moment";


const { Text } = Typography;

type DataSourceType = {
  id: React.Key;
  stu_name?: string;
  pro_contribute_proj?: string;
  grad_year?: string;
};

const defaultData: DataSourceType[] = [
  {
    id: nanoid(),
    stu_name: '',
    pro_contribute_proj: '',
    grad_year: undefined,
  },
  {
    id: nanoid(),
    stu_name: '',
    pro_contribute_proj: '',
    grad_year: undefined,
  },
  {
    id: nanoid(),
    stu_name: '',
    pro_contribute_proj: '',
    grad_year: undefined,
  },
  {
    id: nanoid(),
    stu_name: '',
    pro_contribute_proj: '',
    grad_year: undefined,
  },
  {
    id: nanoid(),
    stu_name: '',
    pro_contribute_proj: '',
    grad_year: undefined,
  }
];

const columns: ProColumns<DataSourceType>[] = [
  {
    title: '姓名',
    dataIndex: 'stu_name',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
  },
  {
    title: '毕业年份',
    dataIndex: 'grad_year',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
    renderFormItem: () => <DatePicker picker="year" style={{ width: '100%' }} />,
  },
  {
    title: '突出贡献项目',
    dataIndex: 'pro_contribute_proj',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
  },
  {
    title: '操作',
    valueType: 'option',
  },
];

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );
  const [dataSource, setDataSource] = useState<DataSourceType[]>(() => defaultData);
  const [editForm] = Form.useForm()
  const download = '2_3_2'
  const status_is_show = history.location.query.flag === 'display'
  const status_is_check = history.location.query.id && history.location.query.fill_id
  const actionRef = useRef<ActionType>();
  const handleSaveBtn = () => {
    console.log("@Save", download)
    const data = {
      fill_id: download,
      data: dataSource
    }
    console.log("@请求数据", data)
    SaveApi('/api/temp-save', data).then(response => {
      if (response.status === 0) {
        Modal.success({
          title: <span>保存成功！</span>,
          onOk() {
            window.location.reload()
          }
        })
      } else {
        ShowError(response.message)
      }
    }, () => {
      ShowError(ServerMessages.error_message)
    })
  }
//上传
  const upload = UploadApi('/api/index/cultivate-talents/graduate-employment/discipline-pioneer-template',
    (info) => {
      console.log("@success", info)
      if (info.file.response.status === 0) {
        const data = info.file.response.data["data_"+download]
        for (let i = 0; i < data.length; i++) {
          data[i].id = nanoid()
          data[i].grad_year = moment(data[i].grad_year, 'YYYY')
        }
        setDataSource(data)
        var id_arr = []
        for (let i = 0; i < data.length; i++) {
          id_arr.push(data[i].id)
        }
        setEditableRowKeys(id_arr)
      } else {
        ShowError(info.file.response.message)
      }
    })

  // 更新
  const [reload, setReload] = useState(false)
  useEffect(() => {
    // 插入
    if (status_is_check) {
      // 审核时加载内容
      SchoolCheckShow(history.location.query.id, history.location.query.fill_id)
        .then(response => {
          console.log(response)
          if (response.status === 0) {
            for (let i = 0; i < response.message.length; i++) {
              response.message[i].id = nanoid()
              // response.message[i].grad_year = response.message[i].grad_year ? moment(response.message[i].grad_year, 'YYYY') : undefined
            }
            setDataSource(response.message)
            // resolve({data: response.message})
          } else {
            // resolve(true)
          }
        })
    } else if (status_is_show) {
      // 查看时加载内容
      ShowApi(download).then(response => {
        console.log("@response", response)
        if (response.status === 0) {
          setDataSource(response.data)
          // resolve({data: response.data})
        }
      })
      // resolve(true)
    } else {
      // resolve({data: dataSource})
      GetSaveApi('/api/show-temp-save', download).then(response => {
        console.log("@response", response)
        if (response.status === 0) {
          for (let i = 0; i < response.data.length; i++) {
            response.data[i].id = nanoid()
            response.data[i].grad_year = response.data[i].grad_year ? moment(response.data[i].grad_year, 'YYYY') : undefined
          }
          setDataSource(response.data);
          var id_arr = []
          for (let i = 0; i < response.data.length; i++) {
            id_arr.push(response.data[i].id)
          }
          setEditableRowKeys(id_arr)
        } else {
          setDataSource(dataSource)
          // resolve({data: dataSource})
        }
      })
    }
    console.log("@update", actionRef.current, dataSource)
  }, [reload])

  // useEffect(() => {
  //   console.log("@editable", dataSource)
  //   for (let i = 0; i < dataSource.length; i++) {
  //     actionRef.current.startEditable(dataSource[i].id);
  //   }
  // }, [dataSource])

  return (
    <PageContainer
      title="学科领域突出贡献者情况"
      content={<Typography.Text type="danger">1. 监测点内涵：2011年至今，在学科领域有突出贡献的毕业生情况。
        <br/>2. 填写20人以内。
        <br/>3. 突出贡献项目：反映毕业生在学科领域作出突出贡献的代表性成果名称，每人填报3项以内。
        <br/>4. 毕业年份：请用“YYYY”格式填写。
        <br/>5. 仅填写当前填报周期内新增的数据，如有删减，请告知学校管理员。
      </Typography.Text>}>
      <Card bordered={false}>
        <ProForm
          onFinish={async () => {
            if (dataSource.length === 0) {
              message.warn("请输入内容")
              return {}
            }
            return new Promise((resolve => {
              editForm.validateFields().then(() => {

                for (let i = 0; i < dataSource.length; i++) {
                  dataSource[i].grad_year = getYear(dataSource[i].grad_year)
                }

                const dataObj = {
                  'data_2_3_2': dataSource
                }
                console.log('@请求数据', dataObj)

                FillApi('/api/index/cultivate-talents/graduate-employment/discipline-pioneer',
                  dataObj, (response) => {
                    message.success(response.message)
                    history.push('/cultivate-talents/graduate-employment')
                    resolve(true)
                  }, (response) => {
                    ShowError(response.message)
                    resolve(false)
                  }, () => {
                    ShowError(ServerMessages.error_message)
                    resolve(false)
                  })

              }, () => {
                resolve(false)
              })
            }))
          }}
          submitter={{
            render: (props, doms) => {
              return <Submitter
                upload={upload}
                download={download}
                doms={doms}
                save={handleSaveBtn}
              />
            },
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: 'none',
              },
            },
            submitButtonProps: {
              style: {
                marginLeft: '-8px'
              }
            },
          }}
        >
          <EditableProTable<DataSourceType>
            pagination={{
              pageSize: 10
            }}
            value={dataSource}
            onChange={setDataSource}
            actionRef={actionRef}
            // request={async () => {
            //
            //   // 如果是审核或者查看,则异步加载内容
            //   return new Promise(resolve => {
            //     if (status_is_check) {
            //       // 审核时加载内容
            //       SchoolCheckShow(history.location.query.id, history.location.query.fill_id)
            //         .then(response => {
            //           console.log(response)
            //           if (response.status === 0) {
            //             resolve({data: response.message})
            //           } else {
            //             resolve(true)
            //           }
            //         })
            //     } else if (status_is_show) {
            //       // 查看时加载内容
            //       ShowApi(download).then(response => {
            //         console.log("@response", response)
            //         if (response.status === 0) {
            //           resolve({data: response.data})
            //         }
            //       })
            //       // resolve(true)
            //     } else {
            //       // resolve({data: dataSource})
            //       GetSaveApi('/api/show-temp-save', download).then(response => {
            //         console.log("@response", response)
            //         if (response.status === 0) {
            //           for (let i = 0; i < response.data.length; i++) {
            //             response.data[i].id = nanoid()
            //             response.data[i].grad_year = response.data[i].grad_year ? moment(response.data[i].grad_year, 'YYYY') : undefined
            //           }
            //           resolve({data: response.data})
            //           for (let i = 0; i < response.data.length; i++) {
            //             actionRef.current.startEditable(response.data[i].id)
            //           }
            //           setDataSource(response.data)
            //         } else {
            //           resolve({data: dataSource})
            //         }
            //       })
            //     }
            //   })
            // }}
            columns={columns}
            rowKey="id"
            recordCreatorProps={{
              newRecordType: 'dataSource',
              record: () => ({
                id: nanoid(),
              }),
              style: {
                display: status_is_show || status_is_check ? 'none' : 'block',
              },
            }}
            editable={{
              type: 'multiple',
              form: editForm,
              editableKeys,
              actionRender: (row, config, defaultDoms) => {
                return [defaultDoms.delete];
              },
              onValuesChange: (record, recordList) => {
                if (record) {
                  setDataSource(recordList);
                } else {
                  // recordList 代表表单的真实数据，但是在空值检测时会变成空值，
                  // 所以只在有输入变化时同步到 DataSource，可以通过 record 来判断是否有输入。
                  // 执行删除操作时，DataSource 应该删掉 recordList 中不存在的项目。
                  let index_list = []
                  for (let i = 0; i < recordList.length; i++) {
                    index_list.push(recordList[i].id)
                  }
                  let newDataSource = []
                  for (let i = 0; i < dataSource.length; i++) {
                    if (index_list.indexOf(dataSource[i].id) !== -1) {
                      newDataSource.push(dataSource[i])
                    }
                  }
                  setDataSource(newDataSource)
                }
              },
              onChange: setEditableRowKeys,
            }}
            style={{marginBottom: 20}}
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};
